<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage, NDataTable, NEllipsis
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, formatDateTime, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '入库' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

import { exportToExcel } from '@/utils/exportUtils'

// 导出方法
const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据 - 假设您的表格数据是通过 api.getDrugsBillsList 获取的
    const { data: tableData } = await api.getDrugsBillsList({
      type:1,
      is_export:1,
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.flatMap(item => {
      const baseData = {
        进货单号: item.id,
        类型: item.type_name,
        备注: item.remark,
        创建人: item.created_uname,
        入库时间: item.add_time
      }

      if (!item.details_mx || item.details_mx.length === 0) {
        return [baseData]
      }

      return item.details_mx.map(detail => ({
        ...baseData,
        单号: detail.id,
        仓库: detail.depository_name,
        药品ID: detail.drugs_id,
        药品名称: detail.drugs?.drugs_name,
        批号: detail.batch,
        批准文号: detail.drugs?.approval_number,
        规格: detail.drugs?.spec,
        单位: detail.drugs?.unit,
        进货单价: detail.unit_price,
        数量: detail.total_number,
        进货总额: detail.total_price,
        过期时间: detail.valid_at,
        供应商: detail.supplier,
        生产厂家: detail.manufacturer
      }))
    })

    // 导出Excel
    exportToExcel(exportData, `入库记录_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    category_id:[]
  },
   config:[],
   durgs:[]
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '入库',
  initForm: {},
  doCreate: api.createDrugsBills,
  doUpdate: api.updateDrugsBills,
  doDelete: api.deleteDrugsBills,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  queryItems.value.type=1
  $table.value?.handleSearch()
  api.getProjectIni().then((res) => (data.data_ini = res.data))
  api.getConfig().then((res) => {
    data.config = res.data
  })
})

const columns = [
    {
    title: '+',
    width: 60,
    key: 'details_mx',
    align: 'center',
    type: 'expand',
    expandable: row => row.details_mx !== null,
    renderExpand: (row) => {
      let details_mx = row.details_mx ?? []
      let sku_columns=[
          {
          width:"auto",
          title: '单号',
          key: 'id'
        },{
          width:"auto",
          title: '仓库',
          key: 'depository_name'
        },
        {
          width:"auto",
          title: '药品id',
          key: 'drugs_id'
        },
        {
          width:"auto",
          title: '药品名称',
          key: 'drugs.drugs_name'
        },
          {
          width:"auto",
          title: '批准文号',
          key: 'drugs.approval_number'
        },
          {
          width:"auto",
          title: '批号',
          key: 'batch'
        },
           {
          width:"auto",
          title: '规格',
          key: 'drugs.spec'
        },
          {
          width:"auto",
          title: '单位',
          key: 'drugs.unit'
        },

          {
          width:"auto",
          title: '进货单价',
          key: 'unit_price'
        }, {
          width:"auto",
          title: '数量',
          key: 'total_number'
        }, {
          width:"auto",
          title: '进货总额',
          key: 'total_price'
        },{
          width:"auto",
          title: '过期时间',
          key: 'valid_at'
        },{
          width:"auto",
          title: '供应商',
          key: 'supplier'
        },
        {
          width:"auto",
          title: '生产厂家',
          key: 'manufacturer'
        },
      ]
      return h(NDataTable, { columns: sku_columns,striped:true ,size:"small",data:details_mx, style: { width: '100%',margin:'10px 0px' }  })
    }
  },
  {
    title: '进货单号',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '类型',
    key: 'type_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },
  //   {
  //   title: '领药人',
  //   key: 'receive_user',
  //   width: 60,
  //   align: 'center',
  //   render(row) {
  //     return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.receive_user })
  //   },
  // },

  {
    title: '供应商',
    key: 'supplier',
    width: 60,
    align: 'center',
    render(row) {
      if (!row.details_mx || !Array.isArray(row.details_mx)) return '--'
      const suppliers = row.details_mx
        .map(item => item.supplier)
        .filter(Boolean)
      
      if (suppliers.length === 0) return '--'
      
      return h(NFlex, { align: "center", justify: "center", wrap: true },
        suppliers.map(supplier =>
          h(NTag, {
            size: "small",
            type: "primary",
            bordered: false,
            style: { margin: '2px' }
          }, {
            default: () => supplier
          })
        )
      )
    },
  },
    {
    title: '创建人',
    key: 'created_uname',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '入库时间',
    key: 'add_time',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },


{
  title: '操作',
  key: 'actions',
  width: 100, // 增加了宽度
  align: 'center',
  fixed: 'right',
  render(row) {
    return [
      // 打印按钮
      withDirectives(
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-right: 5px',
            onClick: () => handlePrint(row)
          },
          {
            default: () => '打印',
            icon: renderIcon('material-symbols:print-outline', { size: 16 }),
          }
        ),
        []
      ),
      // 作废按钮
      h(
        NPopconfirm,
        {
          onPositiveClick: () => handleDelete({ id: row.id }, false),
          onNegativeClick: () => {},
        },
        {
          trigger: () =>
            withDirectives(
              h(
                NButton,
                {
                  size: 'small',
                  type: 'error',
                },
                {
                  default: () => '作废',
                  icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                }
              ),
              []
            ),
          default: () => h('div', {}, '确定作废该数据吗?'),
        }
      ),
    ]
  },
}
]

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const onCreate = () => {
  return {
      depository_id:null,
      drugs_id:null,
      rate:0,
      valid_at:null,
      supplier:null,
    total_number:0
  }
}
function on_add(){
  handleAdd()
  modalForm.value.type=1
  modalForm.value.add_time = formatDateTime(new Date())
  get_ini()
}

function get_ini(){
  api.getDrugsAll().then((res) => (data.durgs = res.data))
}

function findOptionById(options, id) {
  if (!Array.isArray(options)) return null
  for (const opt of options) {
    if (String(opt.id) === String(id)) return opt
    const child = findOptionById(opt.children, id)
    if (child) return child
  }
  return null
}

function onSelectDrug(drugId, rowValue){
  const selected = findOptionById(data.durgs, drugId)
  if (!selected) return
  // 尝试从选中项中提取常见字段并写入当前行
  rowValue.approval_number = selected.approval_number || selected.approvalNumber || ''
  const price = selected.unit_price ?? selected.price ?? selected.unitPrice
  if (price !== undefined && price !== null) {
    rowValue.unit_price = Number(price) || 0
  }
}

// 打印功能
const handlePrint = (row) => {
  // 计算合计数量和金额
  const totalQuantity = row.details_mx?.reduce((sum, item) => sum + (Number(item.total_number) || 0), 0) || 0;
  const totalAmount = row.details_mx?.reduce((sum, item) => sum + (Number(item.total_price) || 0), 0) || 0;

  // 创建打印内容
  const printContent = generatePrintContent(row, totalQuantity, totalAmount);

  // 创建打印窗口
  const printWindow = window.open('', '_blank');
  printWindow.document.write(printContent);
  printWindow.document.close();

  // 打印后自动关闭窗口
  setTimeout(() => {
    printWindow.print();
    printWindow.close();
  }, 500);
}

// 生成打印内容HTML
const generatePrintContent = (row, totalQuantity, totalAmount) => {
  const createDate = row.add_time ? formatDate(new Date(row.add_time)) : formatDate(new Date());
  const uniqueDepositories = [...new Set(
    row.details_mx?.map(item =>
      item.depository_name || ''
    ).filter(Boolean) || []
  )].join('  ');
  console.log(uniqueDepositories);
  // 生成药品行数据
  const generateMedicineRows = () => {
    if (!row.details_mx || row.details_mx.length === 0) {
      return `<tr>
        <td colspan="12" style="text-align:center;">无数据</td>
      </tr>`;
    }

    return row.details_mx.map(item => {

      const targetCategory = data.config.drugscategory.find(
        category => category.id === item.drugs.category_id // 当前药品的类别ID
      );
      const cate_name = targetCategory?.name || '药品类';
      return`
      <tr>
        <td>${item.drugs?.id || 'Y0001'}</td>
        <td>${item.drugs?.drugs_name || ''}</td>
        <td>${cate_name}</td>
        <td>${item.drugs?.spec || '规格'}</td>
        <td>${item.drugs?.unit || '盒'}</td>
        <td>${Number(item.total_number) || 0}</td>
        <td>¥${Number(item.unit_price || 0).toFixed(2)}</td>
        <td>¥${Number(item.total_price || 0).toFixed(2)}</td>
        <td>${item.valid_at || '2025-12-31'}</td>
        <td>${item.id || ''}</td>
        <td>${item.manufacturer || ''}</td>
        <td>${item.approval_number || item.drugs?.approval_number || ''}</td>
      </tr>
    `}).join('');
  };

  return `
  <!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <title>药品进货单 - ${row.id}</title>
    <style>
      * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
        font-family: 'Microsoft YaHei', sans-serif;
      }

      body {
        background-color: white;
        color: #000;
        padding: 10mm;
        font-size: 12px;
        line-height: 1.4;
      }

      .print-container {
        width: 100%;
        margin: 0 auto;
      }

      /* 头部区域样式 - 完全符合图片 */
      .header {
        text-align: center;
        padding-bottom: 5px;
      }

      .title-box {
        margin-bottom: 8px;
      }

      .header-title {
        font-size: 20px;
        font-weight: bold;
        letter-spacing: 2px;
      }

      .main-title {
        font-size: 22px;
        font-weight: bold;
        line-height: 1.8;
      }

      /* 公司信息区域 */
      .company-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        padding-bottom: 5px;
        border-bottom: 2px solid #000;
      }

      .info-section {
        width: 48%;
      }

      .info-row {
        display: flex;
        margin-bottom: 4px;
        font-size: 12px;
      }

      .info-label {
        min-width: 55px;
        font-weight: bold;
        margin-right: 2px;
      }

      /* 表格样式 - 完全符合图片的网格样式 */
      .receipt-table {
        width: 100%;
        border-collapse: collapse;
        margin: 5px 0;
        border: 1px solid #000;
        font-size: 12px;
      }

      .receipt-table th,
      .receipt-table td {
        border: 1px solid #000;
        padding: 4px 3px;
        text-align: center;
        height: 26px;
        white-space: nowrap;
      }

      .receipt-table th {
        background-color: #f0f0f0;
        font-weight: bold;
        color: #000;
      }

      .receipt-table tr {
        page-break-inside: avoid;
      }

      /* 合计区域 */
      .summary {
        margin-top: 5px;
        text-align: right;
        font-size: 13px;
        font-weight: bold;
      }

      /* 签名区域 */
      .signature-section {
        display: flex;
        justify-content: space-between;
        margin-top: 12px;
      }

      .signature-box {
        width: 23%;
      }

      .signature-label {
        font-size: 12px;
        margin-bottom: 2px;
        white-space: nowrap;
      }

      .signature-line {
        border-bottom: 1px solid #000;
        height: 1px;
        width: 100%;
        margin: 5px 0;
      }

      /* 打印日期样式 */
      .print-date {
        text-align: right;
        font-size: 11px;
        margin-top: 3px;
      }

      /* 打印优化 */
      @media print {
        body {
          padding: 5mm !important;
          font-size: 11px;
        }

        .receipt-table th,
        .receipt-table td {
          padding: 3px 2px;
          height: 24px;
          font-size: 11px;
        }

        .signature-section {
          margin-top: 10px;
        }
      }
    </style>
  </head>
  <body>
    <div class="print-container">
      <div class="header">
        <div class="title-box">
          <div class="header-title">杭州泊时</div>
          <div class="main-title">药品进货单</div>
        </div>

        <div class="company-info">
          <div class="info-section">
            <div class="info-row">
              <div class="info-label">单号:</div>
              <div class="info-value">${row.id || '160'}</div>
            </div>
            <div class="info-row">
              <div class="info-label">进货日期:</div>
              <div class="info-value">${createDate}</div>
            </div>
          </div>
          <div class="info-section">
            <div class="info-row">
              <div class="info-label">供应商:</div>
              <div class="info-value">${row.details_mx?.[0]?.supplier || ''}</div>
            </div>
            <div class="info-row">
              <div class="info-label">仓库:</div>
              <div class="info-value">${uniqueDepositories || ''}</div>
            </div>
          </div>
        </div>
      </div>

      <table class="receipt-table">
        <thead>
          <tr>
            <th width="7%">编号</th>
            <th width="15%">名称</th>
            <th width="7%">类别</th>
            <th width="7%">规格</th>
            <th width="7%">单位</th>
            <th width="7%">数量</th>
            <th width="7%">进货价</th>
            <th width="7%">金额</th>
            <th width="9%">有效期</th>
            <th width="7%">批号</th>
            <th width="10%">生产厂家</th>
            <th width="10%">批准文号</th>
          </tr>
        </thead>
        <tbody>
          ${generateMedicineRows()}
        </tbody>
      </table>

      <div class="summary">
        合计数量: ${totalQuantity}<br>
        进货总额: ¥${Number(totalAmount).toFixed(2)}
      </div>

      <div class="signature-section">
        <div class="signature-box">
          <div class="signature-label">质量情况：</div>
          <div class="signature-line"></div>
        </div>
        <div class="signature-box">
          <div class="signature-label">验收结论：</div>
          <div class="signature-line"></div>
        </div>
        <div class="signature-box">
          <div class="signature-label">验收人：</div>
          <div class="signature-line"></div>
        </div>
        <div class="signature-box">
          <div class="signature-label">复核人：</div>
          <div class="signature-line"></div>
        </div>
      </div>

      <div class="print-date">打印日期: ${formatDate(new Date())}</div>
    </div>
  </body>
  </html>
  `;
}

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton style="margin-left: 1350px;" type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getDrugsBillsList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="操作时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 1700px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-tabs type="line" animated size="large" pane-style="padding: 20px 0 0 0;">
              <n-tab-pane name="基础信息">
                 <NFormItem label="入库时间" path="add_time">
                  <n-date-picker
                    v-model:formatted-value="modalForm.add_time"
                    type="datetime"
                    clearable
                    placeholder="请输入入库时间"
                    style="width: 100%"
                  />
                </NFormItem>

                <NFormItem label="备注" path="remark">
                  <NInput type="textarea" v-model:value="modalForm.remark" clearable placeholder="请输入备注" />
                </NFormItem>

              </n-tab-pane>
              <n-tab-pane name="单据明细">
                <NFormItem label="" path="details">
                  <n-layout>
                        <n-layout-header>
                          <n-flex >
                            <n-tag size="large" style="width: 100px"> 仓库 </n-tag>
                            <n-tag size="large" style="width: 400px"> 药品 </n-tag>
                            <n-tag size="large" style="width: 120px"> 批号 </n-tag>
                            <n-tag size="large" style="width: 150px"> 批准文号 </n-tag>
                            <n-tag size="large" style="width: 120px"> 进货单价(元) </n-tag>
                            <n-tag size="large" style="width: 100px"> 数量</n-tag>
                            <n-tag size="large" style="width: 130px">有效期</n-tag>
<!--                            <n-tag size="large" style="width: 150px"> 批准文号 </n-tag>-->
                            <n-tag size="large" style="width: 150px"> 供应商 </n-tag>
                            <n-tag size="large" style="width: 150px"> 生产厂家 </n-tag>
                          </n-flex>
                        </n-layout-header>
                        <n-layout-content content-style="padding: 10px 0;" >

                          <n-dynamic-input v-model:value="modalForm.details" :on-create="onCreate">
                            <template #default="{ value , index}">
                              <n-flex justify="space-between">
                                <NSelect
                                  v-model:value="value.depository_id"
                                  :options="data.config.depository"
                                  placeholder="请选择仓库"
                                  filterable
                                  label-field="name"
                                  value-field="id"
                                  style="width: 100px"
                                />
                                <n-cascader style="width: 400px;" v-model:value="value.drugs_id"
                                  clearable
                                  placeholder="请选择药品"
                                  :options="data.durgs"
                                  cascade
                                  check-strategy="children"
                                  show-path
                                  filterable
                                  clear-filter-after-select
                                  :render-label="(info) => h(NEllipsis, { style: 'max-width: 240px' , tooltip: true }, { default: () => info.label || info.name })"
                                  :max-tag-count="3"
                                  label-field="name"
                                  value-field="id"
                                  @update:value="(v) => onSelectDrug(v, value)"
                                />
                                <NInput placeholder="批号" v-model:value="value.batch" style="width: 120px"/>
                                <NInput placeholder="批准文号" disabled v-model:value="value.approval_number" style="width: 150px"/>

                                <n-input-number :min="0" placeholder="进货单价" v-model:value="value.unit_price" style="width: 120px"/>
                                <n-input-number :min="0" placeholder="数量" v-model:value="value.total_number" style="width: 100px"/>

                                <n-date-picker
                                  v-model:formatted-value="value.valid_at"
                                  value-format="yyyy-MM-dd"
                                  type="date"
                                  clearable
                                  placeholder="过期时间"
                                  style="width: 130px"
                                />
<!--                                <n-input-number :min="0" placeholder="批准文号" v-model:value="value.approval_number" style="width: 150px"/>-->

                                <NSelect
                                  v-model:value="value.supplier"
                                  :options="data.config.gongying"
                                  placeholder="供应商"
                                  filterable
                                  label-field="name"
                                  value-field="name"
                                  style="width: 150px"
                                />
                                <NSelect
                                  v-model:value="value.manufacturer"
                                  :options="data.config.manufacturers"
                                  placeholder="生产厂家"
                                  filterable
                                  label-field="name"
                                  value-field="name"
                                  style="width: 150px"
                                />
                              </n-flex>
                            </template>
                          </n-dynamic-input>
                        </n-layout-content>
                      </n-layout>
                </NFormItem>
               </n-tab-pane>
            </n-tabs>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
